import { find, get, keyBy } from 'lodash';
import config from 'config'; // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
import dayjs from 'dayjs';
import superagent from 'superagent';
import utc from 'dayjs/plugin/utc';
import { Op } from 'sequelize';
import { getSequelize } from '../db';
import ReservationPrepayModel from '../models/reservation-prepay';

import HotelModel from '../models/hotel';
import OpenUserModel from '../models/open-user';
import RoomHistoryModel from '../models/room-history';
import { WxPrepayPaidStatus, getToday } from '../utils';

dayjs.extend(utc);

function getTodayUTC() {
  return dayjs().startOf('days').format('YYYY-MM-DD HH:mm:ss');
}

function getTomorrowUTC() {
  return dayjs().add(1, 'days').startOf('days')
    .format('YYYY-MM-DD HH:mm:ss');
}

class DashboardController {
  async getAdminTotal(req, res, next) {
    try {
      const sequelize = getSequelize();
      const hotels = await HotelModel.findAll({
        attributes: [sequelize.literal('count(1) as total')],
        raw: true
      });

      const members = await OpenUserModel.findAll({
        attributes: [sequelize.literal('count(1) as total')],
        raw: true
      });
      const today = getToday();

      const revenue = await ReservationPrepayModel.findAll({
        attributes: [sequelize.literal('sum(amount) as revenue')],
        where: { business_date: today, paid_status: WxPrepayPaidStatus.Success },
        raw: true
      });

      const rooms = await RoomHistoryModel.findAll({
        attributes: [sequelize.literal('count(1) as total')],
        where: { business_date: today },
        raw: true
      });

      console.log(hotels, members, revenue, rooms);

      res.sendOk({
        hotels: get(hotels, '0.total', 0),
        members: get(members, '0.total', 0),
        revenue: get(revenue, '0.revenue', 0),
        rooms: get(rooms, '0.total', 0)
      });
    }
    catch (e) {
      next(e);
    }
  }

  async getOfflineInterface(req, res, next) {
    try {
      const today = getToday();

      const hotels = await HotelModel.findAll({
        where: {
          begin_date: { [Op.lte]: today },
          end_date: { [Op.gte]: today },
        },
        raw: true
      });

      const offlines = [];
      const service = config.get('localService');
      for (const hotel of hotels) {
        try {
          const response = await superagent.get(`${service}/interface/online/${hotel.id}`)
            .set('Content-Type', 'application/json')
            .accept('application/json')
            .query({ method: 'get', api: `interface/online` }); // query string

          console.log(response.data)
          if (!(response.status === 200 && get(response, 'body.data'))) {
            offlines.push(hotel);
          }
        } catch (e) {
          console.error('superagent request error', e);
          offlines.push(hotel);
        }
      }

      res.sendOk(offlines);
    }
    catch (e) {
      next(e);
    }
  }

  async getAnalysisTotal(req, res, next) {
    try {
      const { hotel_id } = req.user;
      const sequelize = getSequelize();

      const membersToday = await OpenUserModel.findAll({
        where: {
          hotel_id,
          created_at: {
            [Op.gte]: getTodayUTC(),
            [Op.lt]: getTomorrowUTC()
          }
        },
        attributes: [sequelize.literal('count(1) as total')],
        raw: true
      });

      const membersTotal = await OpenUserModel.findAll({
        where: {
          hotel_id
        },
        attributes: [sequelize.literal('count(1) as total')],
        raw: true
      });

      const today = getToday();

      const revenue = await ReservationPrepayModel.findAll({
        attributes: [sequelize.literal('sum(amount) as revenue')],
        where: { hotel_id, business_date: today, paid_status: WxPrepayPaidStatus.Success },
        raw: true
      });

      const rooms = await RoomHistoryModel.findAll({
        attributes: [sequelize.literal('count(1) as total')],
        where: { hotel_id, business_date: today },
        raw: true
      });

      console.log(membersToday, membersTotal, revenue, rooms);

      res.sendOk({
        membersToday: get(membersToday, '0.total', 0),
        membersTotal: get(membersTotal, '0.total', 0),
        revenue: get(revenue, '0.revenue', 0),
        rooms: get(rooms, '0.total', 0)
      });
    }
    catch (e) {
      next(e);
    }
  }

  // // 会员来源
  // async getMemberSource(req, res, next) {
  //   try {
  //     const { hotel_id } = req.user;
  //     const sequelize = getSequelize();

  //     const data = await Names.findAll({
  //       attributes: ['state_id', sequelize.literal('ifnull(any_value(name), "unknown") state_name'), sequelize.literal('count(`Names`.`id`) total')],
  //       include: [{
  //         model: States,
  //         as: 'state',
  //         required: false,
  //         attributes: []
  //       }],
  //       where: {
  //         hotel_id
  //       },
  //       group: 'state_id',
  //       order: [sequelize.literal('any_value(sequence)')],
  //       raw: true
  //     });

  //     res.sendOk(data);
  //   }
  //   catch (e) {
  //     next(e);
  //   }
  // }

  // // 每周会员消费频次
  // async getMemberWeeklyConsumption(req, res, next) {
  //   try {
  //     const { hotel_id } = req.user;
  //     const sequelize = getSequelize();
  //     let weekBegin = dayjs().startOf('week');
  //     // console.log('第一天', dayjs().weekday(0).startOf('days').toISOString());
  //     const todayWeek = dayjs().day(); // 今天星期几?

  //     if (todayWeek === 0) { // 今天周日, 那么这周的开始日期为上周一
  //       weekBegin = weekBegin.day(-6);
  //     }
  //     else { // 这周的开始为本周一
  //       weekBegin = weekBegin.add(1, 'day');
  //     }

  //     const begin_date = weekBegin.format('YYYY-MM-DD');
  //     const data = await TransactionDetails.findAll({
  //       attributes: ['business_date', sequelize.literal('count(1) as total')],
  //       where: {
  //         hotel_id,
  //         business_date: {
  //           [Op.gte]: begin_date
  //         },
  //         transaction_type: 'REVENUE',
  //         amount: {
  //           [Op.gt]: 0
  //         }
  //       },
  //       group: 'business_date',
  //       order: [['business_date', 'ASC']],
  //       raw: true
  //     });

  //     res.sendOk(data);
  //   }
  //   catch (e) {
  //     next(e);
  //   }
  // }

  // 每月支付金额
  async getMemberMonthlyPayments(req, res, next) {
    try {
      const { hotel_id } = req.user;
      const sequelize = getSequelize();

      const year = dayjs().year();
      const periods = [];

      for (let x = 1; x < 13; x++) {
        periods.push({ period: `${year}-${('0' + x).slice(-2)}`, amount: 0 });
      }

      const yearBegin = dayjs().startOf('year');

      const begin_date = yearBegin.format('YYYY-MM-DD');
      const data = await ReservationPrepayModel.findAll({
        attributes: [sequelize.literal('left(business_date, 7) as period'),
        sequelize.literal('ifnull(sum(amount),0) amount')
        ],
        where: {
          hotel_id,
          business_date: {
            [Op.gte]: begin_date
          },
          paid_status: WxPrepayPaidStatus.Success
        },
        group: sequelize.literal('left(business_date, 7)'),
        order: sequelize.literal('left(business_date, 7)'),
        raw: true
      });

      console.log(data)
      for (const item of periods) {
        item.amount = get(find(data, { period: item.period }), 'amount', 0);
      }

      res.sendOk(periods);
    }
    catch (e) {
      next(e);
    }
  }

  // // 主体来源
  // async getHotelSource(req, res, next) {
  //   try {
  //     const sequelize = getSequelize();

  //     const data = await HotelModel.findAll({
  //       attributes: ['state_id', sequelize.literal('ifnull(any_value(`state`.`name`), "unknown") state_name'), sequelize.literal('count(`Hotels`.`id`) total')],
  //       include: [{
  //         model: States,
  //         as: 'state',
  //         required: false,
  //         attributes: []
  //       }],
  //       group: 'state_id',
  //       order: [sequelize.literal('any_value(sequence)')],
  //       raw: true
  //     });

  //     res.sendOk(data);
  //   }
  //   catch (e) {
  //     next(e);
  //   }
  // }

  // // 全系统每周会员消费频次
  // async getAdminMemberWeeklyConsumption(req, res, next) {
  //   try {
  //     const sequelize = getSequelize();
  //     let weekBegin = dayjs().startOf('week');
  //     // console.log('第一天', dayjs().weekday(0).startOf('days').toISOString());
  //     const todayWeek = dayjs().day(); // 今天星期几?

  //     if (todayWeek === 0) { // 今天周日, 那么这周的开始日期为上周一
  //       weekBegin = weekBegin.day(-6);
  //     }
  //     else { // 这周的开始为本周一
  //       weekBegin = weekBegin.add(1, 'day');
  //     }

  //     const begin_date = weekBegin.format('YYYY-MM-DD');
  //     const data = await TransactionDetails.findAll({
  //       attributes: ['business_date', sequelize.literal('count(1) as total')],
  //       where: {
  //         business_date: {
  //           [Op.gte]: begin_date
  //         },
  //         transaction_type: 'REVENUE',
  //         amount: {
  //           [Op.gt]: 0
  //         }
  //       },
  //       group: 'business_date',
  //       order: [['business_date', 'ASC']],
  //       raw: true
  //     });

  //     res.sendOk(data);
  //   }
  //   catch (e) {
  //     next(e);
  //   }
  // }
}

export default new DashboardController();
